<template>
  <div style="padding: 20px" class="app-container">
    <el-row :gutter="20">
      <el-col :span="5">
        <div>
          <el-tag>指标</el-tag>
        </div>
        <div class="left_menu">
          <el-tag @click="clickTag(item)" :key="item.id" v-for="(item,index)  in quotaData">{{ item.name }}</el-tag>
        </div>
      </el-col>
      <el-col :span="19">
        <div class="grid-content app-container">
          <el-row>
            <el-col :span="4" :offset="9" :push="1">
              <el-input v-model="listDimensionParams.key" clearable placeholder="请输入关键词"></el-input>
            </el-col>
            <el-col :span="2" :push="1">
              <el-button type="primary" icon="el-icon-search"
                         @click="getListDimension">搜索
              </el-button>
            </el-col>
            <el-col :span="3" :offset="6">
              <el-button type="primary" icon="el-icon-check" @click="submitData">
                关联维度
              </el-button>
            </el-col>
          </el-row>
          <div class="dndList">
            <el-row>
              <el-col :span="10">
                <div :style="{width:width1}" class="dndList-list">
                  <h3>{{ list1Title }}</h3>
                  <draggable :set-data="setData" animation=500 @add="addElement" @remove="removeElement" :list="list1"
                             group="article"
                             class="dragArea">
                    <div v-for="element in list1" :key="element.id" class="list-complete-item">
                      <div class="list-complete-item-handle">
                        {{ element.activeYear }} {{ element.dimensionName }}[{{ element.dimensionCode }}]
                      </div>
                      <div style="position:absolute;right:0px;">
            <span style="float: right ;margin-top: -20px;margin-right:5px;" @click="deleteEle(element)">
              <i style="color:#ff4949" class="el-icon-delete"/>
            </span>
                      </div>
                    </div>
                  </draggable>
                </div>
              </el-col>
              <el-col :span="10">
                <div :style="{width:width2}" class="dndList-list">
                  <h3>{{ list2Title }}</h3>
                  <draggable :list="list2" animation=500 group="article" class="dragArea">
                    <div v-for="element in list2" :key="element.id" class="list-complete-item">
                      <div class="list-complete-item-handle2" @click="pushEle(element)">
                        {{ element.activeYear }} {{ element.dimensionName }} [{{ element.dimensionCode }}]
                      </div>
                    </div>
                    <pagination
                      small
                      v-show="dimensionAllCount>0"
                      :total="dimensionAllCount"
                      :pager-count="5"
                      :page-sizes="[10]"
                      :page-size="10"
                      layout="total, sizes, prev, pager, next, jumper"
                      :page.sync="listDimensionParams.current"
                      :limit.sync="listDimensionParams.size"
                      @pagination="getListDimension"
                    />
                  </draggable>
                </div>
              </el-col>
            </el-row>

          </div>
        </div>
      </el-col>
    </el-row>
  </div>


</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import draggable from 'vuedraggable'
import { insertRelation, queryDim,listDimension } from '@/api/quota/define/define.js'
import { strMapToObj } from '@/api/quota/common/common.js'
//例如：import 《组件名称》 from '《组件路径》';
export default {
  name: 'joinDimension',
  //使用import引入外部组件需要在components对象中注册才可以使用
  components: { draggable },
  props: {
    list1: {
      type: Array,
      default() {
        return []
      }
    },
    list2: {
      type: Array,
      default() {
        return []
      }
    },
    list1Title: {
      type: String,
      default: '已关联维度'
    },
    list2Title: {
      type: String,
      default: '可选择维度'
    },
    width1: {
      type: String,
      default: '100%'
    },
    width2: {
      type: String,
      default: '100%'
    }
  },
  data() {
    //这里存放数据
    return {
      quotaData: [],
      clickQuotaId: Number,
      dimensionAllCount: 0,
      resultMap: new Map(),
      listDimensionParams: {
        pageNum: 0,
        pageSize: 10,
        orderField: 'UPDATE_DATE',
        order:"desc",
        key: ''
      }
    }
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    submitData() {
      let obj = strMapToObj(this.resultMap)
      insertRelation(obj).then(res => {
        if (res.data) {
          this.msgSuccess('关联关系已提交')
          this.resultMap.clear()
          this.$store.dispatch('tagsView/delView', this.$router.history.current)
          this.$router.push({ path: '/quota/quotaDefine' })
        }
      })
    },
    //添加元素触发事件
    addElement(val) {
      this.cacheAdd()
    },
    //删除元素触发事件
    removeElement(val) {
      this.cacheRemove()
    },
    //缓存添加
    cacheAdd() {
      let resultList = this.resultMap.get(this.clickQuotaId.toString())
      for (let i = 0; i < this.list1.length; i++) {
        let index = resultList.findIndex(item => {
          return item.id == this.list1[i].id
        })
        if (index == -1) {
          let newObj = { ...this.list1[i] }
          resultList.push(newObj)
        }
      }
    },
    //缓存删除
    cacheRemove() {
      let resultList = this.resultMap.get(this.clickQuotaId.toString())
      for (let i = 0; i < resultList.length; i++) {
        let index = this.list1.findIndex(item => {
          return item.id == resultList[i].id
        })
        if (index == -1) {
          resultList.splice(i, 1)
        }
      }
    },
    //拖拽效果的方法
    isNotInList1(v) {
      return this.list1.every(k => v.id !== k.id)
    },
    isNotInList2(v) {
      return this.list2.every(k => v.id !== k.id)
    },
    deleteEle(ele) {
      for (const item of this.list1) {
        if (item.id === ele.id) {
          const index = this.list1.indexOf(item)
          this.list1.splice(index, 1)
          this.cacheRemove()
          break
        }
      }
      if (this.isNotInList2(ele)) {
        this.list2.unshift(ele)
      }
    },
    pushEle(ele) {
      for (const item of this.list2) {
        if (item.id === ele.id) {
          const index = this.list2.indexOf(item)
          this.list2.splice(index, 1)
          break
        }
      }
      if (this.isNotInList1(ele)) {
        this.list1.push(ele)
        this.cacheAdd()
      }
    },
    setData(dataTransfer) {
      dataTransfer.setData('Text', '')
    },
    //tag点击事件 这里要查询维度
    clickTag(val) {
      this.clickQuotaId = val.id
      this.getDimensionListByQuotaId(val.id)
      //每次点击刷新全部列表
      this.getListDimension()
    },
    getListDimension() {
      listDimension(this.listDimensionParams).then((res) => {
        this.list2 = res.data.list
        this.dimensionAllCount = res.data.totalCount
      })
    },
    getDimensionListByQuotaId(quotaId) {
      //如果缓存里有直接在缓存里取 避免覆盖展示数据
      let arr = this.resultMap.get(quotaId.toString())
      if (arr.length <= 0) {
        queryDim(quotaId).then((res) => {
          this.list1 = res.data==null?[]:res.data
          let resultList = [...res.data]
          this.resultMap.set(quotaId.toString(), resultList)
        })
      } else {
        this.list1 = [...this.resultMap.get(quotaId.toString())]
      }

    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.quotaData = this.$route.params.quotaData
    this.getListDimension()
    this.quotaData.forEach(item => {
      this.resultMap.set(item.id.toString(), [])
    })
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  },
  beforeCreate() {
  }, //生命周期 - 创建之前
  beforeMount() {
  }, //生命周期 - 挂载之前
  beforeUpdate() {
  }, //生命周期 - 更新之前
  updated() {
  }, //生命周期 - 更新之后
  beforeUnmount() {
  }, //生命周期 - 销毁之前
  unmounted() {
  }, //生命周期 - 销毁完成
  activated() {
  } //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>

:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.left_menu {
  width: 100%;
  height: 500px;
  overflow: auto;
  padding: 20px;
  background: #eee;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.el-tag {
  margin-bottom: 5px;
  display: flex;
  justify-content: center;
}

.dndList {
  background: #fff;
  padding-bottom: 40px;

&
:after {
  content: "";
  display: table;
  clear: both;
}

.dndList-list {
  float: left;
  padding-bottom: 30px;

&
:first-of-type {
  margin-right: 2%;
}

.dragArea {
  margin-top: 15px;
  min-height: 50px;
  padding-bottom: 30px;
}

}
}

.list-complete-item {
  cursor: pointer;
  position: relative;
  font-size: 14px;
  padding: 5px 12px;
  margin-top: 4px;
  border: 1px solid #bfcbd9;
  transition: all 1s;
}

.list-complete-item-handle {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 50px;
}

.list-complete-item-handle2 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 20px;
}

.list-complete-item.sortable-chosen {
  background: #4AB7BD;
}

.list-complete-item.sortable-ghost {
  background: #30B08F;
}

.list-complete-enter,
.list-complete-leave-active {
  opacity: 0;
}

h3 {
  text-shadow: 5px 5px 5px #36a3f7;
}

</style>
